#include "listnode.h"

/*
https://leetcode.cn/problems/merge-k-sorted-lists
*/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    if (!list1)
    {
        return list2;
    }
    if (!list2)
    {
        return list1;
    }
    struct ListNode* head = NULL;
    if (list1->val < list2->val)
    {
        head = list1;
        list1->next = mergeTwoLists(list1->next, list2);
    }
    else
    {
        head = list2;
        list2->next = mergeTwoLists(list1, list2->next);
    }

    return head;
}

struct ListNode* mergeK(struct ListNode** lists, int start, int end)
{
    if (start >= end)
    {
        return lists[start];
    }

    int mid = start + (end - start) / 2;
    struct ListNode* list1 = mergeK(lists, start, mid);
    struct ListNode* list2 = mergeK(lists, mid + 1, end);
    return mergeTwoLists(list1, list2);
}

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
    if (!listsSize || !lists)
    {
        return NULL;
    }
    return mergeK(lists, 0, listsSize - 1);
}